﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;
using Newtonsoft.Json.Linq;
namespace WinHBM.Core.Net.Http
{

    public enum RequestMethod
    {
        GET,
        POST,
    }

    

    public class WebRequest
    {

        /// <summary>
        /// 公共Header
        /// </summary>
        public static Dictionary<string, string> CommonHeaders = new Dictionary<string, string>();

        /// <summary>
        /// 自定义Header
        /// </summary>
        public Dictionary<string, string> Headers = new Dictionary<string, string>();


        /// <summary>
        /// 请求地址
        /// </summary>
        public string Url { get; set; }


        /// <summary>
        /// 请求方法
        /// </summary>
        public RequestMethod RequestMethod = RequestMethod.GET;

        /// <summary>
        /// 请求体
        /// </summary>
        public JObject RequestBody { get; set; }


        private HttpClient client;


        public WebRequest(HttpClient client)
        {
            this.client = client;
            //初始化公共Header
            this.InitHeaders();
        }

        private void InitHeaders()
        {
            foreach (string key in WebRequest.CommonHeaders.Keys)
            {
                this.Headers[key] = WebRequest.CommonHeaders[key];
            }
        }

        public byte[] GetRequestBody()
        {
            if(this.RequestBody == null)
            {
                return null;
            }
            return Encoding.UTF8.GetBytes(this.RequestBody.ToString());
        }

        public HttpWebRequest createHttpRequest()
        {
            Uri uri = new Uri(this.Url);
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(uri);
            //RequestMethod
            request.Method = this.RequestMethod.ToString();

            //ContentType
            //if(this.RequestMethod == RequestMethod.POST)
            //{
                request.ContentType = String.IsNullOrEmpty(this.Headers["Content-Type"]) ? "" : this.Headers["Content-Type"];
            //}
            
            //Headers
            foreach (string key in this.Headers.Keys)
            {
                if(key.Equals("Content-Type") || key.Equals("Content-type") || key.Equals("content-type"))
                {
                    continue;
                }
                request.Headers.Set(key, this.Headers[key]);
            }
            return request;
        }

        public void send(OnSuccess OnSuccess,OnError OnError)
        {
            this.client.execute(this, OnSuccess, OnError);
        }

        public void send(OnSuccess OnSuccess)
        {
            this.client.execute(this, OnSuccess,null);
        }


        /*public JObject send()
        {
            return this.client.execute(this);
        }*/
    }
}
